package com.lw.leetcode.node;

import com.lw.leetcode.node.Node;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @Author liw
 * @Date 2021/4/19 12:47
 * @Version 1.0
 */
public class Preorder {



    public List<Integer> postorder(Node root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Stack<Node> stack = new Stack<>();
        Stack<Boolean> flag = new Stack<>();
        stack.push(root);
        flag.push(false);
        while (!stack.isEmpty()) {
            Boolean f = flag.pop();
            if (f) {
                Node node = stack.pop();
                list.add(node.val);
            } else {
                flag.push(true);
                Node node = stack.peek();
                List<Node> children = node.children;
                if (children != null && !children.isEmpty()) {
                    for (int i = children.size() - 1; i >= 0 ; i--) {
                        stack.push(children.get(i));
                        flag.push(false);
                    }
                }
            }

        }
        return list;
    }

}
